﻿using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Menu;
using Application = Autodesk.Revit.ApplicationServices.Application;

namespace RevitAddin
{
    [TransactionAttribute(TransactionMode.Manual)]
    [RegenerationAttribute(RegenerationOption.Manual)]
    public class JGCodeCMD : IExternalEventHandler
    {
        public string code { get; set; }
        public Action<List<ConnectorItem>> action { get; set; }

        public void Execute(UIApplication app)
        {
            UIDocument uidoc = app.ActiveUIDocument;
            Document doc = uidoc.Document;
            Application revitApp = app.Application;

            try
            {

                Reference refer = uidoc.Selection.PickObject(ObjectType.Element, "请选择设备终点");

                FamilyInstance fi = doc.GetElement(refer) as FamilyInstance;

                if (fi != null)
                {
                    Parameter para = fi.LookupParameter("注释");
                    if (para != null)
                    {
                        Transaction ts = new Transaction(doc, Guid.NewGuid().ToString().Substring(0, 10));
                        ts.Start();

                        para.Set(code);

                        ts.Commit();

                    }
                    ConnectorSet cs = fi.MEPModel.ConnectorManager.Connectors;
                    List<ConnectorItem> ciList = new List<ConnectorItem>();
                    ConnectorSetIterator interator = cs.ForwardIterator();
                    while (interator.MoveNext())
                    {
                        Connector conn = interator.Current as Connector;
                        if (conn != null)
                        {
                            ConnectorItem ci = new ConnectorItem();
                            ci.XYZ = comMethod.RoundXYZ(new XYZ(conn.Origin.X, conn.Origin.Y, conn.Origin.Z));
                            ci.TFCode = conn.Description;
                            ciList.Add(ci);
                        }
                    }
                    action?.Invoke(ciList);
                }

            }
            catch (Exception ex)
            {
                TaskDialog.Show("温馨提示1", "\n" + ex.Message + ex.StackTrace);
            }
        }

        public string GetName()
        {
            return "JGCodeCMD";
        }
    }

}
